﻿using System.Windows;
using System.Windows.Controls;

namespace BaseControls
{
    /// <summary>
    /// Helper that can find class in xaml.
    /// </summary>
    public class LogicalTreeHelper
    {
        /// <summary>
        /// Method that find object in xaml. 
        /// </summary>
        /// <param name="controlName">The name to find</param>
        /// <param name="rootElement">Start element</param>
        /// <returns>If object is finded method return this object otherwise null</returns>
        public static UIElement FindName(string controlName,FrameworkElement rootElement)
        {
            FrameworkElement root = rootElement as FrameworkElement;
            while (root != null)
            {
                Panel panel = root as Panel;//some component can be contained in other component and not be Panel
                object frameControl = root.FindName(controlName);                
                if (frameControl != null)//if frameControl is in some root what is not main root;                
                    return frameControl as UIElement;
                
                if (panel != null)                
                    root = (panel as FrameworkElement).Parent as FrameworkElement;                
                else
                    root = root.Parent as FrameworkElement;
            }
            return null;
        }
    }
}
